<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ganqqwerty
 * Date: 11.04.12
 * Time: 23:51
 * To change this template use File | Settings | File Templates.
 */
class SAFHooks
{
    /*!
     * This function is calling on hook smwStorePageData, i.e. each time the semantic information is changed
     * during the page changes or update jobs
     * @param semdata SMWSemanticData object that have all the information of the semantic data for the given page
     */
    public static function smwStorePageData(SMWSemanticData &$semdata)
    {
        global $wgSAFVotePropertyName;
        //TODO: check whether articlefeedback property exists and if not, create it
        $id = $semdata->getSubject()->getTitle()->getArticleID();//XXX DANGER! It's probably not the id I need!
//        wfDebugLog( 'smw', 'id for the page: ' . print_r( $id, true ) );
        $avgVote = SemanticArticleFeedback::calculateAvgVote($id);
        if(is_null($avgVote)) {
            return true;
        }

        self::createVoteProperty();

        $propName = isset($wgSAFVotePropertyName)? $wgSAFVotePropertyName:"ArticleFeedbackVote";
        $semdata->addPropertyObjectValue(SMWDIProperty::newFromUserLabel($propName),
             SMWDataItem::newFromSerialization(SMWDataItem::TYPE_NUMBER, $avgVote));
        //       wfDebugLog( 'smw', 'It\'s working now: ' . print_r( $semdata, true ) );
        return true;
    }

    /**
     * @static
     * If property doesn't exists then we'll
     */
    public static function createVoteProperty()
    {
        global $wgSAFVotePropertyName;
        $propName = isset($wgSAFVotePropertyName)? $wgSAFVotePropertyName:"ArticleFeedbackVote";
        $p = WikiPage::factory(Title::newFromDBkey("Property:$propName"));
        wfDebugLog( 'smw', "ArticleFeedbackVote property doesnt exitsts. Creating $propName", print_r($p    ));

        if(!$p->exists() || $p->isRedirect()) {
            $p->doEdit("[[has type::number]]", "create articlefeedbackvote");
        }
    }

    /*!
     * when someone vote via ArticleFeedback extension we will make a null edit of the pages that has been voted
     * we do that for semantic mediawiki hook is to be run
     * @param params havent't been used
    */
    public static function articleFeedbackChangeRating($params) {
         $wikiPage=new WikiPage(Title::newFromID($params[pageid]));
        $wikiPage->doEdit($wikiPage->getText(), "");
        return true;
    }



}
